package com.gy.paidao.util;

import android.content.Context;
import android.util.Log;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author GY
 * @date 16/1/21
 * @Description:文件下载
 */
public class IMFileModel {

    private static IMFileModel instance;
    private StorageUtils storageUtils;
    public final Context context;

    public static IMFileModel getInstance(Context context){
        if(instance == null){
            instance = new IMFileModel(context);
        }
        return instance;
    }

    private IMFileModel(Context context){
        this.context = context;
    }

    public void downFile(final String  path,final IMUploadSuccessListener listener,final String type,final String id){
        try {
            File file = StorageUtils.getNormaoDirectory(context);
            final String fileName = file.getAbsolutePath()+"/"+id+"."+type;
            LogUtil.e(fileName);
            // 打开文件获取输出流，文件不存在则自动创建
            final File fileNew = new File(fileName);
            if(fileNew.exists()){
                listener.messageUploadFileSuccess(fileName);
                return;
            }

            Request request = new Request.Builder().url(path).get().build();
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    listener.messageUploadFail(path);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    byte[] bytes = response.body().bytes();
                    if(bytes.length > 0){

                        FileOutputStream fos = new FileOutputStream(fileNew);
                        fos.write(bytes);
                        fos.close();
                        listener.messageUploadFileSuccess(fileName);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("Exception-----");
            listener.messageUploadFail(path);
        }

    }

}
